<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <link href="../../css/style.css" rel="stylesheet" type="text/css"/>
    <style type="text/css">
        td{word-break: break-all; word-wrap:break-word;}
    </style>
    <title>Say Hi Page</title>
</head>
<body>
<script src="../../js/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../js/JPageController.js" type="text/javascript"></script>
<script src="../../js/comm.js" type="text/javascript"></script>
<script src="../../js/My97DatePicker/WdatePicker.js" type="text/javascript"></script>
<script src="../../js/util.js" type="text/javascript"></script>
<script src="../../js/JBusinessCom.js" type="text/javascript"></script>
<script src="../../js/jquery.autocomplete.min.js" type="text/javascript"></script>
    <div id="loading"></div>
    <table style="min-width: 882px;" width="100%" border="0" height="100%" cellspacing="0" cellpadding="0">
        <tr>
            <td valign="top" bgcolor="#e6e6e8" class="main">
                   <table width="100%" border="0" cellspacing="0" cellpadding="0" height="500">
                       <tr>
                         <td valign="top">
                                <div class="buttonArea">
                                    <div class="left">
                                        <a class="button blueButton PERM_ADD" onclick="addRecord()">新增销售单</a>
                                        <a class="button PERM_EMP" onclick="Export()">导出</a>
                                    </div>

                                   <form action="/Sale/List" method="post"><input id="WriteBack" name="WriteBack" type="hidden" value="" />
                                       <div class="right">
                                            <span class="fl">
                                                <input type="checkbox" checked="checked" id="chkZF" value="0" onclick="reload()" />
                                                <label for="chkZF">&nbsp;不显示作废单据</label>&nbsp;&nbsp;&nbsp;&nbsp;</span>
                                            <span id="simpleSearch">
                                                <input class="inputText fl" id="SearchSaleKey" name="SearchSaleKey" placeholder="请输入模糊关键字" size="30" type="text" value="" />
                                                <a class="button" onclick="reload()" id="search">搜索</a></span>
                                            <a class="button" id="aAdvanced">高级搜索</a>
                                </div>
                                       <span id="message" style="color:red;font-size: 18px"></span>
                                   <div class="searchAdvanced" style="display: none;" id="highSearch">
                                        <input id="Advanced" name="Advanced" type="hidden" value="" />
                                      <table  width="98%" border="0" cellspacing="0" cellpadding="8">
                                          <tr>
                                              <td width="70" align="right">创建日期</td>
                                              <td  width="272">
                                                    <input class="inputText" id="SearchCreateStartDate" name="SearchCreateStartDate" onClick="WdatePicker()" readonly="true" size="10" type="text" value="" />
                                                    <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
                                                    <input class="inputText" id="SearchCreateEndDate" name="SearchCreateEndDate" onClick="WdatePicker()" readonly="true" size="10" type="text" value="" />
                                               </td>
                                              <td width="70" align="right">客户</td>
                                               <td>
                                                 <input class="inputText wf100" id="SearchClient" name="SearchClient" type="text" value="" />
                                                </td>
                                              <td width="70" align="right">经手人</td>
                                               <td><input class="inputText wf100" id="SearchUser" name="SearchUser" type="text" value="" />
                                                </td>
                                          </tr>
                                          <tr>
                                              <td width="70" align="right">业务日期</td>
                                               <td>
                                                   <input class="inputText" id="SearchStartDate" name="SearchStartDate" onClick="WdatePicker()" readonly="true" size="10" type="text" value="" /> <span>&nbsp;&nbsp;~&nbsp;&nbsp;</span>
                                                    <input class="inputText" id="SearchEndDate" name="SearchEndDate" onClick="WdatePicker()" readonly="true" size="10" type="text" value="" />
                                                </td>
                                              <td align="right">制单人</td>
                                              <td><input  class="inputText wf100" id="SearchCreateUser" name="SearchCreateUser" type="text" value="" />
                                               </td>
                                              <td align="right">仓库</td>
                                              <td>
                                                    <select class="inputSelect" style="width:100%" id="WarehouseId" name="WarehouseId" style="width:120px; border: 1px solid #D7D7D7;">
                                                    </select>
                                                </td>
                                          </tr>
                                          <tr>
                                              <td align="center" colspan="6">
                                                    <a href="javascript:;" class=" button blueButton"  onclick="reload()" id="searchAdvance">开始搜索</a>
                                                </td>
                                          </tr>
                                     </table>


                                   </div>

                           </form>
                        </div>
                        <!-- buttonArea -->
                        <div class="clear height10"></div>
                         <div class="shadowBoxWhite tableDiv">
                             <input type="hidden" id="url" />
                           <div id="dvOrders">
                             <table width="100%" border="0" cellspacing="1" cellpadding="5" id="resultTable"></table>
                           </div>
                                 </div>
                        <!-- tableDiv -->
                         </td>
                      </tr>
                   </table>
             </td>
         </tr>
    </table>


</body>
</html>
<!--MvcPager 1.5 for ASP.NET MVC 3.0 © 2009-2011 Webdiyer (http://www.webdiyer.com)-->
<script type="text/javascript">//<![CDATA[
function _MvcPager_Keydown(e){var _kc,_pib;if(window.event){_kc=e.keyCode;_pib=e.srcElement;}else if(e.which){_kc=e.which;_pib=e.target;}var validKey=(_kc==8||_kc==46||_kc==37||_kc==39||(_kc>=48&&_kc<=57)||(_kc>=96&&_kc<=105));if(!validKey){if(_kc==13){ _MvcPager_GoToPage(_pib,2);}if(e.preventDefault){e.preventDefault();}else{event.returnValue=false;}}}function _MvcPager_GoToPage(_pib,_mp){var pageIndex;if(_pib.tagName=="SELECT"){pageIndex=_pib.options[_pib.selectedIndex].value;}else{pageIndex=_pib.value;var r=new RegExp("^\\s*(\\d+)\\s*$");if(!r.test(pageIndex)){alert("页索引无效");return;}else if(RegExp.$1<1||RegExp.$1>_mp){alert("页索引超出范围");return;}}var _hl=document.getElementById(_pib.id+'link').childNodes[0];var _lh=_hl.href;_hl.href=_lh.replace('*_MvcPager_PageIndex_*',pageIndex);if(_hl.click){_hl.click();}else{var evt=document.createEvent('MouseEvents');evt.initEvent('click',true,true);_hl.dispatchEvent(evt);}_hl.href=_lh;}
//]]>
$(document).ready(function(){
       //首先检查权限
    var result = checkAuthority("Sale/QuerySales");
    if (!result){
        //给出提示信息
        Dialog.alert("对不起，您无操作权限!");
        //关闭当前页面
        parent.CloseTabByTitle("销售历史");
        return;
    }
});

var sortorder = "";
var usortname = "";
  /*--排序--*/
function Sort(sortname) {
    if (usortname == sortname) {
        if (sortorder == 'asc')
            sortorder = "desc";
        else
            sortorder = "asc";
    }
    else{
        usortname = sortname;
        sortorder = "desc";
    }
    requestJson["SortName"] = usortname;
    requestJson["SortOrder"] = sortorder;
    reload();
}

//供排序使用
function setSortView() {
    //初始化排序图标
    if (sortorder == 'asc')
        $('#' + usortname).addClass("Oup");
    else if(sortorder == 'desc')
        $('#' + usortname).addClass("Odown");
}
</script>
<script type="text/javascript">
    $(document).ready(function () {
        //打印
        var isPrint = requestUrlPara("IsPrint");
        var printSaleId = requestUrlPara("SaleId");
        if (isPrint == 1) {
            OpenPrint('/Sale/Print?SaleId=' + printSaleId);
        }
        var isToList = requestUrlPara("IsToList");
        if (isToList == 1) {
            parent.CloseTabByTitle('新增销售');
            parent.CloseTabByTitle('复制新增销售单');
            parent.CloseTabByTitle('借出转销售')
        }
        var employeeheader = { EmployeeCode: "帐号", EmployeeName: "经手人" };
        $("#SearchUser").autoComplete({
            header: employeeheader,
            url: "/shared/queryemployee",
            width: 220,
            selected: function (o) {
                $("#SearchUser").val(o.EmployeeName);
            }
        });
    });
    // 导出
    function Export() {
        try {
            requestJson["IsOpenSaleTaxRate"] = IsOpenSaleTaxRate;
            var recordList = parent.sale_bi.exportSaleList(JSON.stringify(requestJson));
            recordList = eval("(" + recordList + ")");
            var IsSuccess = recordList["IsSuccess"];
            var Message = recordList["Message"];
            if (IsSuccess) {
                var src=recordList["Data"];
                parent.$.messager.confirm('系统提示', '文件导出成功，是否打开导出文件所在的目录？', function (r) {
                    if (r)
                       parent.file_bi.openDirectory(src);
                });
            }else
                Dialog.alert(Message);

        } catch (e) {
            Dialog.alert("exception=" + e);
        }
    }

    // 新增记录
    function addRecord() {
        if (!AddOrEditBySOBState('', false)) {
            return;
        }
        parent.childAddTab('新增销售', "/sale-add.html", '慧管货');
    }

    function moreSearch() {
        var height = $(".searchArea").height();
        if (height > 40) {
            $(".searchArea").height(33);
        }
        else {
            $(".searchArea").height(73);
        }
    }
    // 重新加载数据
    function reload() {
        requestJson["Page"] = 1;
        requestJson["rp"] = 10
        querySaleList();
        setSortView();
//        MVCPage(getPageParams());
    }

    // 编辑
    function editRecord(arg) {
        parent.childAddTab('销售单据详细', "Sale/Edit.html?SaleId=" + arg + "&Flag=false", '慧管货');
    }

    // 复制新增
    function copyRecord(arg) {
        if (!AddOrEditBySOBState('', false)) {
            return;
        }
        parent.childAddTab('复制新增销售单', "/sale-add.html?list=copyAdd&Flag=false" + "&saleId=" +arg , '慧管货');
    }

    function WriteBack(arg) {
        if (!AddOrEditBySOBState('', false)) {
            return;
        }
        if(!validateSobState()){
            return;
        }
        var reqJson = {}
        reqJson["SaleId"] = arg;
        parent.$.messager.confirm('系统提示', '确定要作废这张单据吗？', function (r) {
            if (r) {
                var rqJson = {}
                rqJson["SaleId"] = arg;
                var result = parent.sale_bi.judgeSaleHasReturn(JSON.stringify(rqJson))
                var resultList = eval("(" + result +")");
                if(resultList["count"] > 0){
                    Dialog.alert("请先作废退货单！")
                    return;
                }
                var rpJson = parent.sale_bi.deleteSale(JSON.stringify(reqJson))
                var result = eval("(" + rpJson + ")");
                if(result["IsSuccess"] ==  1){
                    reload();
                    Dialog.alert("作废销售单成功")

                }else{
                    Dialog.alert("作废销售单失败");
                }
            }
        });
    }
    $(function () {
        $("#chkZF").attr("checked", true);
        $("#Advanced").val(1);
        $("#simpleSearch").show();
        $(".searchAdvanced").hide();
        $("#aAdvanced").removeClass("searchAdvancedS");

    });

        //高级查询按钮
        $("#aAdvanced").click(function () {
            $("#highSearch input[name != 'Advanced']").val("");
            $("#SearchSaleKey").val("");
            if ($("#Advanced").val() == "0") {
                $("#Advanced").val(1);
                $("#simpleSearch").show();
                //$("#aAdvanced").text("简单搜索")
                $("#aAdvanced").addClass("searchAdvancedS");
            } else {
                $("#Advanced").val(0);
                $("#simpleSearch").hide();
                //$("#aAdvanced").text("高级搜索");
                $("#aAdvanced").removeClass("searchAdvancedS");
            }
            $(".searchAdvanced").slideToggle("slow");

           //初始化仓库
            var wh_list = parent.warehouse_bi.queryWarehouseDropDownList("{}");
            wh_list = eval("(" + wh_list + ")");
            $('#WarehouseId').html(('<option value="">所有仓库</option>')+(buildSelectOption(wh_list['Data'], 'WarehouseId', 'WarehouseName', false)));
        });

    //得到高级查询的参数
    function getHighQueryParam(){
        var searchCreateStartDate = $("#SearchCreateStartDate").val();
        var searchCreateEndDate = $("#SearchCreateEndDate").val();
        var searchClient = $("#SearchClient").val().trim();
        var searchUser = $("#SearchUser").val().trim();
        var searchStartDate = $("#SearchStartDate").val();
        var searchEndDate = $("#SearchEndDate").val();
        var searchCreateUser = $("#SearchCreateUser").val().trim();
//        var warehouseName = $("#WarehouseId option:selected").text();
        var warehouseName
        if($("#WarehouseId").val() == null){
            warehouseName = ""
        }else{
            warehouseName = $("#WarehouseId").val();
        }
             requestJson["SearchCreateStartDate"] = searchCreateStartDate;
             requestJson["SearchCreateEndDate"] = searchCreateEndDate;
             requestJson["SearchClient"] = searchClient;
             requestJson["SearchUser"] = searchUser;
             requestJson["SearchStartDate"] = searchStartDate;
             requestJson["SearchEndDate"] = searchEndDate;
             requestJson["SearchCreateUser"] = searchCreateUser;
             requestJson["WarehouseName"] = warehouseName;
    }


</script>

<script type="text/javascript">
    var IsOpenSaleTaxRate;
         var requestJson = {
                "SortName": "CreateDate",
                "SortOrder": "desc",
//                "IsStop":'',
                "Page": 1,
                "rp": 10
            };
 //查询销售历史列表
    function querySaleList() {
        var sysconf = getSysConfig();
        sysconf = eval("(" + sysconf + ")");
        IsOpenSaleTaxRate = sysconf['IsOpenSaleTaxRate'];
        if(IsOpenSaleTaxRate == undefined){
            IsOpenSaleTaxRate = 0
        }
        $("#resultTable").html("");
        try {
            if ($("#chkZF").attr("checked")){
                requestJson["WriteBack"] = '0';
            }else{
                requestJson["WriteBack"] = '1';
            }
            getHighQueryParam();
                requestJson["SearchSaleKey"] = $("#SearchSaleKey").val().trim();
            var recordList = parent.sale_bi.querySaleList(JSON.stringify(requestJson));
            recordList = eval("(" + recordList + ")");
            if(recordList["IsSuccess"] == '0'){
                Dialog.alert(recordList["Message"])
                return;
            }

            var tableResult = creatHeadHtml();
            var deleteTableResult = [];
            var curPage = recordList["CurPage"];
            var pageCount = recordList["PageCount"];
            var recordCount = recordList["RecordCount"];
            var isBackGoods = recordList["IsBackGoods"];
//            var index = 0;
//            var unDelIndex = 0;
            if(recordList["Data"].length > 0){
                for(var i = 0; i < recordList["Data"].length; i++){
                    var record = recordList["Data"][i];
                    tableResult = tableResult + createDataRow(record,i,curPage,isBackGoods)
                }
                tableResult = tableResult +totalAmt(recordList)+ creatLastRow(curPage,pageCount,recordCount);
            }else{
                tableResult = tableResult +noQueryData();
            }
            $("#resultTable").html(tableResult)
            var record = recordList[recordList.length - 1];

//            alert(recordList.length);
            //$("#saleNum").html(record['SaleAmt']);
        } catch (e) {
            alert("exception="+e)
        }
    }

    //没有查到数据时
    function noQueryData(){
        var result = ' <div class="clear height10"></div>'+
           '<div class="shadowBoxWhite">'+
                '<table align="center">'+
                    '<tr>'+
                        '<td align="center" style="background-color: #FFFFFF">'+
                            '<p>&nbsp;</p>'+
                            '<p>'+
                              ' <img src="../../images/nodata_sale.png" />'+
                            '</p>'+
                            '<p class="fontNodata">'+
                                '当前还没有任何销售单<br />'+
                            '</p>'+
                            '<p><a class="button blueButton PERM_ADD" onclick="addRecord()">新增销售单</a></p>'+
                            '<p>&nbsp;</p>'+
                        '</td>'+
                    '</tr>'+
                '</table>'+
        '</div>'
        return result;

    }
  //创建查询列表的最后一行
    function creatLastRow(curPage,pageCount,recordCount){
        var oriStr =
                  '<tr id="lastLine">'
                  if(IsOpenSaleTaxRate == "1"){
                     oriStr = oriStr + '    <td colspan="11" align="left" valign="middle" bgcolor="#FFFFFF">'
                  }else{
                      oriStr = oriStr + '    <td colspan="10" align="left" valign="middle" bgcolor="#FFFFFF">'
                  }

                  oriStr = oriStr + '        {pager_context}'+
                  '    </td>'+
                  '</tr>';
        var oriStr = oriStr.replace("{pager_context}",creatPageController(curPage,pageCount,recordCount,"querySaleList();",6));
        return oriStr;
    }

    $(window).load(function () {
        querySaleList();
        setSortView();
    });

     // 创建表头html
    function creatHeadHtml(){
        var oriStr =
                 '<tr>'+
                    '<th width="20" align="center" style="display: none;">'+
                        '<input type="checkbox" onclick="SelAll(this);" name="selectall" /></th>'+
                    '<th width="30" align="center">序号</th>'+
                    '<th align="center" width="80">'+
                        '<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#dvOrders" href="javascript:;" class="Ohead" id="SaleDate" onclick="Sort(\'SaleDate\')">业务日期</a>'+
                    '</th>'+
                    '<th align="center" width="135">'+
                        '<a data-ajax="true" data-ajax-mode="replace" data-ajax-update="#dvOrders" href="javascript:;" class="Ohead" id="SaleNo" onclick="Sort(\'SaleNo\')">单据编号</a>'+
                    '</th>'+
                    '<th width="100" align="center">客户名称</th>'+
                    '<th align="left">销售商品</th>';
                      if(IsOpenSaleTaxRate == '1'){
                           oriStr = oriStr +'<th width="80" align="center" name="IsOpenSaleTaxRate_1">税后应收(元)</th>'
                       }else{
                          oriStr = oriStr +'<th width="80" align="center" name="IsOpenSaleTaxRate_1">应收金额(元)</th>'
                      }
                   oriStr = oriStr + '<th width="80" align="center">已收金额(元)</th>'+

                    '<th width="80" align="center">结算方式</th>'+
                    '<th width="80" align="center">出库仓库</th>'+
                    '<th width="120" align="center">操作</th>'+
                '</tr>'
        return oriStr;
    }

     //创建数据行
    function createDataRow(record,index,page,isBackGoods){
        var saleId = record['SaleId'];
        var saleDate = record['SaleDate'].substring(0,10);
        var saleNo = record['SaleNo'];
        var clientName = record['ClientName'];
        var accountSimpleName = record['AccountSimpleName'];
        var afterTaxAmt = getSystemDecimal(record['AfterTaxAmt']);
        if(afterTaxAmt != ""){
            afterTaxAmt = getSystemDecimal(afterTaxAmt);
        }
        var warehouseName = record['WarehouseName'];
        var receAmt = getSystemDecimal(record['StrReceAmt']);
        var productName = record['ProductName'];
        var writeBack = record["WriteBack"];
        var oriStr = "";

              if(writeBack == '0'){
                  if($.inArray(saleId,isBackGoods)!=-1){
                        oriStr = oriStr + '<tr> <td align="center"  bgcolor="#FFFFFF">'+
                        '<div class="returnGoodsIcon"></div>'
                  }else{
                      oriStr = oriStr +  '<tr> <td bgcolor="#FFFFFF" align="center">'+ (((page-1)*10)+(index+1))
                  }
              }else{
                  oriStr = oriStr + '<tr  class="cancel"> <td align="center"  bgcolor="#FFFFFF">'+
                        '<div class="cancelIcon"></div>'
              }
          oriStr = oriStr +  '    </td>'+
              '    <td bgcolor="#FFFFFF" align="center">'+saleDate+
              '    </td>'+
              '    <td bgcolor="#FFFFFF" align="center">'+saleNo+'</td>'+
              '    <td align="center" bgcolor="#FFFFFF">'+ replaceHtmlTag(clientName) +'</td>'+
              '    <td align="left" bgcolor="#FFFFFF">'+ replaceHtmlTag(productName) +'</td>'
//              if(IsOpenSaleTaxRate == '1'){
//                   oriStr = oriStr + '    <td align="center" bgcolor="#FFFFFF" naem="IsOpenSaleTaxRate_1">'+ record["FAReceAmt"] +'</td>'
//                }else{
              oriStr = oriStr + '    <td align="center" bgcolor="#FFFFFF" naem="IsOpenSaleTaxRate_1">'+ getSystemDecimal(record["FAReceAmt"]) +'</td>'
//              }
              oriStr = oriStr + '    <td align="center" bgcolor="#FFFFFF">'+ receAmt +'</td>'+
              '    <td align="center" bgcolor="#FFFFFF">'+ replaceHtmlTag(accountSimpleName) +'</td>'+
              '    <td align="center" bgcolor="#FFFFFF">'+ replaceHtmlTag(warehouseName) +'</td>'+
              '    <td align="center" bgcolor="#FFFFFF">'+
                            '<a class="operate details" onclick="editRecord(\''+ saleId + '\')" title="查看详细"></a>'+
                            '<a class="operate copy" onclick="copyRecord(\''+ saleId + '\')" title="复制新增"></a>';
        if(writeBack == '0'){
           oriStr = oriStr + '<a class="operate del" onclick="WriteBack(\''+ saleId + '\')" title="作废"></a>'
        }
         oriStr = oriStr + '</td></tr>'
        return oriStr;
    }

    //创建合计行
    function totalAmt(recordList){
        var totalTr = '<tr>'+
                    '<td bgcolor="#FFFFFF" align="right" colspan="5">合计：'+
                    '</td>'
                     if(IsOpenSaleTaxRate == "1"){
                          totalTr = totalTr + '<td align="center" bgcolor="#FFFFFF"><span class="fontRed">￥</span><span class="font14 fontRed">'+getSystemDecimal(recordList['TotalAfterTaxAmtStr'])+'</span><span class=" font18 fontRed"></span></td>'
                       }else{
                            totalTr = totalTr + '<td align="center" bgcolor="#FFFFFF"><span class="fontRed">￥</span><span class="font14 fontRed">'+getSystemDecimal(recordList['TotalFaPayAmt'])+'</span><span class=" font18 fontRed"></span></td>'
                         }
                   totalTr = totalTr +  '<td align="center" bgcolor="#FFFFFF"><span class="fontRed">￥</span><span class="font14 fontRed">'+ getSystemDecimal(recordList["TotalRealPayAmt"]) +'</span><span class=" font18 fontRed"></span></td>'+
                   '<td align="center" bgcolor="#FFFFFF">&nbsp;</td>'+
                      '<td align="center" bgcolor="#FFFFFF">&nbsp;</td>'+
                    '<td align="center" bgcolor="#FFFFFF">&nbsp;</td>'+
                '</tr>';
        return totalTr;
    }

function validateSobState(){
    //验证帐套状态
            var sobState = GetSOBState();
            if (sobState == "2") {
                Dialog.alert("该账套已封账，不能操作！", function () {
                    window.location.href = "List.html";
                });
                return false;
            } else if (sobState == "3") {
                parent.$.messager.defaults = {
                            ok:"去解锁",
                            cancel:"取消"
                        };
                    parent.$.messager.confirm('系统提示', '提示：当前账套已锁定，请先解锁账套！', function (r) {
                            if(r)
                            {
                                parent.childAddTab('历史盘点单','StoreReserve/List.html','慧管货');

                            }
                            parent.$.extend(parent.$.messager.defaults, {
                                ok: "确定",
                                cancel: "取消"
                            });
                        });

                    return false;
            } else if (sobState != "1") {
                Dialog.alert("当前帐套不是开账状态！请先开账！", function () {
                    window.location.href = "List.html";
                })
                return false;
            }else{
                return true;
            }

}
</script>

